var hospitalId;
var departmentId;
$(function(){
	$("#imgSignCode").attr("src","../signcode/get?rc="+Math.random());
	//构建角色列表
	$("#gridUser").datagrid({
	    width: "100%",
	    height: 'auto',
	    url: "../doctor/listData?random="+Math.random(),
	    method: 'get',
	    sortName: 'title',
	    loadMsg: "数据加载中...",
	    pagination:true,
	    pageSize: 19,//每页显示的记录条数，默认为10
	    pageList:[19,20,30],//每页显示几条记录
	    singleSelect:true,
	    toolbar:"#tbUser"
	});
});

/**构建用户状态列
 * val: the field value，也就是field:'id'。
 * row: the row record data。就是这一行的Json数据，包括你已经选择在Datagrid上显示的内容，和没显示的内容。
 * index:索引号
 * @returns 状态中文名
 */
function stateColumn(val,row,index)
{
	var userState="";
	switch(Number(val))
	{
	case 0:
		userState="启用";
		break;
	case 1:
		userState="停用";
		break;
	case 2:
		userState="未激活";
		break;
	}
	return userState;
}

//条件查询
function search()
{
	var doctorName=$("#txtSearchDoctorName").val();
	$('#gridUser').datagrid('load',{
		  name:doctorName
	});
}

//清空表单
function clearUserFrom()
{

	$("#frmUser").form('clear');
}

//打开人员编辑对话框
function dlgUserOpen()
{
	$("#dlgUser").window('open');
}

//打开新增用户对话框
function dlgUserOpenAdd()
{     

	//jsFrmUser();
	$("#txtOpType").val("add");
	hospitalId=null;
    departmentId=null;
    $('#portrait').css("display","none");
    $("#imgSend").attr("src","");
	clearUserFrom();
	//获取医院列表
	listHospital();
	dlgUserOpen();
}

//取消人员编辑
function dlgUserCancel()
{
	$("#dlgUser").window('close');
	clearUserFrom();
}

//提交表单
function submitForm()
{   
	var opType=$("#txtOpType").val();
	//新增
	if(opType=="add")
	{
		addSubmit();
	}
	
	//修改
	if(opType=="edit")
	{
		editSubmit();
	}
}

/**
 * 修改用户状态
 * @param userId
 * @param state
 * @param userName
 */
function editUserState(userId,state,userName)
{
	
	var stateName=state==0?"停用":"启用";
	var stateE=state==0?1:0;
	
	$.messager.confirm("提示", "是否<font color='red'><b>"+stateName+"</b></font>用户【"+userName+"】？", function(r){
		if (r){
			$.ajax({
				type: "get",
				url: "../user/editState",
				data:{
					userId:userId,
					state:stateE
				},
				success: function(data){
					if(data.result==true)
					{
						$("#gridUser").datagrid("load",{data:{random:function(){return Math.random();}}});
					}
					else
		            {
		            	$.messager.alert("提示",data.msg,"error");
		            }
				},
				error:function(err){
					$.messager.alert("提示",err.responseText,null,function(){
						window.location.href="../login/toLogin";
					});
				}
			});
		}
	});
}

/**
 * 构建操作列
 * val: the field value，也就是field:'id'。
 * row: the row record data。就是这一行的Json数据，包括你已经选择在Datagrid上显示的内容，和没显示的内容。
 * index:索引号
 */
function optColumn(val,row,index)
{
	var stateName=row.state==0?"停用":"启用";
	var optStr="<a href='javascript:void(0)' onclick='javascript:delUser("+val+",\""+row.name+"\")' style='color:blue'><u>删除</u></a>";
	optStr+="&nbsp;";
	optStr+="<a href='javascript:void(0)' onclick='javascript:editUserState("+row.userId+","+row.state+",\""+row.name+"\")' style='color:blue'><u>"+stateName+"</u></a>";
	optStr+="&nbsp;";
	optStr+="<a href='javascript:void(0)' onclick='javascript:dlgUserOpenEdit("+val+","+index+")' style='color:blue'><u>编辑</u></a>";
	return optStr;
}

//新增用户提交
function addSubmit()
{
	if($("#hospitalId").val()==''){
		$("#hospitalId").focus();
		$.messager.alert("提示","所属医院不能为空","error");
		return false;
	}
	if($("#departmentId").val()==''){
		$("#departmentId").focus();
		$.messager.alert("提示","所属科室不能为空","error");
		return false;
	}
	$('#frmUser').form('submit',{  
      url:'../doctor/save',  
      onSubmit:function(){
          return $(this).form('validate');
      },  
      success:function(jsonstr){
      	var data=JSON.parse(jsonstr); 
          if(data.result==true)
          {
          	//提交成功处理
          	//dlgUserCancel();
          	
          	$('#frmUser').form('clear');
          	$("#gridUser").datagrid("load",{data:{random:function(){return Math.random();}}});
          	$.messager.alert("提示",data.msg);
          }
          else
          {
          	$.messager.alert("提示",data.msg,"error");
          }
      }
  }); 
}
/**
 * 打开修改用户对话框
 * @param userId:用户ID
 * @param rowIndex:表格索引号
 */
function dlgUserOpenEdit(id,rowIndex)
{
	clearUserFrom();
	$('#gridUser').datagrid('selectRow',rowIndex);
	var doctor=$('#gridUser').datagrid('getSelected');	
	$('#portrait').css("display","block");
	$("#imgSend").attr("src",doctor.img);
	$("#txtdoctorId").val(doctor.id);
	$("#txtCreateDate").val(doctor.createDate);
	$("#txtname").textbox("setValue",doctor.name);
	$("#userId").val(doctor.userId);
	//$("#img").textbox("setValue",doctor.img);	
	hospitalId=doctor.hospitalId;//医生下拉框值
	departmentId=doctor.departmentId//科室下拉框值
	$("#introduction").textbox("setValue",doctor.introduction);
	$("#description").val(doctor.description);
	$("#txtOpType").val("edit");
	//获取医院列表
	listHospital();
	//获取科室列表
	createSelCity();
	//获取用户信息
	userBean(doctor.userId);
	dlgUserOpen();
}

//获取user用户信息
function userBean(userId){
	$.ajax({
			type: "get",
			url: "../user/selUser",
			data:{
				'id':userId
			},
			success: function(data){
				$("#userName").textbox("setValue",data.userName);
				$("#password").textbox("setValue",data.password);
			}
	});
	
}
//修改用户提交
function editSubmit()
{	
	if($("#hospitalId").val()==''){
		$("#hospitalId").focus();
		$.messager.alert("提示","所属医院不能为空","error");
		return false;
	}
	if($("#departmentId").val()==''){
		$("#departmentId").focus();
		$.messager.alert("提示","所属科室不能为空","error");
		return false;
	}if($("#hospitalId").val()==''){
	$("#hospitalId").focus();
	$.messager.alert("提示","所属医院不能为空","error");
	return false;
}
if($("#departmentId").val()==''){
	$("#departmentId").focus();
	$.messager.alert("提示","所属科室不能为空","error");
	return false;
}
	$('#frmUser').form('submit',{  
        url:'../doctor/edit',  
        onSubmit:function(){
            return $(this).form('validate');
        },  
        success:function(jsonstr){
        	var data=JSON.parse(jsonstr); 
            if(data.result==true)
            {
            	//提交成功处理
            	dlgUserCancel();
            	$("#gridUser").datagrid("load",{data:{random:function(){return Math.random();}}});
            	$.messager.alert("提示",data.msg);
            }
            else
            {
            	$.messager.alert("提示",data.msg,"error");
            }
        }
    }); 
}
/**
 * 删除用户
 * @param userId 用户ID
 * @param userName 用户名
 */
function delUser(id,name)
{
	$.messager.confirm("提示", "是否删除用户【"+name+"】？", function(r){

		if (r){
			$.ajax({
				type: "get",
				url: "../doctor/delete",
				data:{
					'id':id
				},
				success: function(data){
					if(data.result==true)
					{
						$("#gridUser").datagrid("load",{data:{random:function(){return Math.random();}}});
					}
					else
		            {
		            	$.messager.alert("提示",data.msg,"error");
		            }
				},
				error:function(err){
					$.messager.alert("提示",err.responseText,null,function(){
						window.location.href="../login/toLogin";
					});
				}
			});
		}
	});
}
//*******************************************以下为下拉框function*******************************************************
//获取医院列表 赋值下拉狂
function listHospital(){
	$.ajax({
        async : false,  
        cache : true,
        type : 'post',  
        url : '../hospital/grade/next',
        success:function(data){
        	
        	var hospitalStr="<option value=''>请选择医院</option>";
        	for(var i=0;i<data.length;i++)
        	{ 
        		var hospital=data[i];
        		if(hospitalId==hospital.id){
        			hospitalStr+="<option value='"+hospital.id+"' selected=selected>"+hospital.name+"</option>";
        			
        		}else{
        		hospitalStr+="<option value='"+hospital.id+"'>"+hospital.name+"</option>";
        		}
        	}
        	$("#hospitalId").html(hospitalStr);

        }
	})
	
}

//获取科室列表 赋值下拉框
function createSelCity(){
		 hospitalId=$("#hospitalId").val();
	$.ajax({
        async : false,  
        cache : true,
        type : 'post',  
        url : '../hospitalDepartment/grade/next',
		data:{
			'hospitalId':hospitalId
		},
        success:function(data){
        	
        	var departmentStr="<option value=''>请选择科室</option>";
        	for(var i=0;i<data.length;i++)
        	{ 
        		var department=data[i];
        		if(departmentId==department.id){
        			departmentStr+="<option value='"+department.id+"' selected=selected>"+department.name+"</option>";
        		}else{
        		departmentStr+="<option value='"+department.id+"'>"+department.name+"</option>";
        		}
        	}
	  $("#departmentId").html(departmentStr);

        }
	})
}
